package com.longway.common.ws;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SecurityXMLServer implements Runnable {
    private ServerSocket server;
    private BufferedReader reader;
    private BufferedWriter writer;
    private String xml;

    public SecurityXMLServer() {
        createServerSocket(843);
        new Thread(this).start();
    }

    //启动服务器
    private void createServerSocket(int port) {
        try {
            server = new ServerSocket(port);
            System.out.println("启动flash策略服务器服务监听端口：" + port);
        } catch (IOException e) {
            System.exit(1);
        }
    }

    //启动服务器线程
    @Override
    public void run() {
        while (true) {
            Socket client = null;
            try {
                //接收客户端的连接
                client = server.accept();

                InputStream in = client.getInputStream();

                byte[] buffer = new byte[23];
                if (in.read(buffer) != -1 && (new String(buffer, "ISO-8859-1"))
                        .startsWith("<policy-file-request/>")) {
                    OutputStream out = client.getOutputStream();
                    byte[] bytes = ("<?xml version=\"1.0\"?>\n"
                            + "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\n"
                            + "<cross-domain-policy> \n"
                            + "   <site-control permitted-cross-domain-policies=\"master-only\"/>\n"
                            + "   <allow-access-from domain=\"*\" to-ports=\"*\" />\n"
                            + "</cross-domain-policy>").getBytes("ISO-8859-1");
                    out.write(bytes);
                    out.write(0x00);
                    System.out.println("写入完成");
                    out.flush();
                    out.close();
                } else {

                }
            } catch (Exception e) {
            }finally {
                try {
                    client.close();
                } catch (Exception ex2) {

                }
            }
        }
    }

    //测试主函数
    public static void main(String[] args) {
        new SecurityXMLServer();
    }
}

